<?php

namespace Aoe\Attributes\Controller;

use Aoe\Attributes\ClassInterface;
use Aoe\Core\Controller;
use Aoe\Core\Kernel;
use Aoe\Intent\Request\Request;
use Attribute;
use Closure;

/**
 * # 渲染文件
 *
 * @noinspection PhpUnused
 *
 */
#[Attribute(Attribute::TARGET_CLASS)]
class Explore implements ClassInterface
{
    const string VIEW_START          = '自动查找视图';
    const string VIEW_COMPLETE       = '离开视图解析';
    const string ERR_TEMP_NOT_FOUND  = '未找到视图${file}';

    use Middleware;

    /**
     * @param Kernel $kernel
     * @param Controller $obj
     * @return void
     */
    public function forClass(Kernel $kernel, $obj): void
    {
        $obj->setMiddleware($this->inject($obj));
    }

    protected function core(Request $request, Controller $controller, ?Closure $next): void
    {
        $next && $next($request);
        if ($request->response->completed) return;

        $controller->recorder->Log(self::VIEW_START);
        $action = $request->section->action;
        $html   = $this->_display_view($controller, $action, $request->getParam());
        if ($html) $request->response->complete($html);
        $controller->recorder->Log(self::VIEW_COMPLETE);
    }


    /**
     * ## 渲染操作
     *
     * @param Controller $controller
     * @param string $view
     * @param array $arguments
     *
     * @return string|false
     *
     */
    private function _display_view(Controller $controller, string $view, array $arguments = []): string | false
    {
        $file = $this->_get_view_file_name($controller, ucfirst($view));
        $controller->recorder->Log($file);
        $html = $controller->kernel->Template()->display($file, $arguments);
        if (!$html) $controller->recorder->Log(self::ERR_TEMP_NOT_FOUND, ['file' => $file]);
        return $html;
    }

    /**
     * ## 模板文件名
     *
     * @param Controller $controller
     * @param string $view
     * @return string
     */
    private function _get_view_file_name(Controller $controller, string $view): string
    {
        $dir  = $controller->module->vir;
        $ds   = DIRECTORY_SEPARATOR;
        $name = strtolower($controller->name);
        return "$dir$ds$name$ds$view";
    }
}